package ru.nlezhnev.data_models;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import ru.nlezhnev.utils.PhpDecoder;
import ru.nlezhnev.utils.PhpEncoder;
import flex.messaging.io.amf.ASObject;

public class FarmActionsModel {
	static final private String GET_SQL = "SELECT income_action FROM farm_user_actions WHERE vkontact_id = ? ORDER BY date ASC";
	static final private String ADD_SQL = "INSERT INTO farm_user_actions (row_user_action_id, income_action, vkontact_id, date) VALUES (NULL, ?, ?, ?)";
	static final private String DELETE_SQL = "DELETE FROM farm_user_actions WHERE vkontact_id = ? AND date <= ?";
	
	private Connection conn;
	private int uid;
	private ArrayList<ASObject> actions = new ArrayList<ASObject>();
	private ArrayList<ASObject> addedActions = new ArrayList<ASObject>();
	
	public FarmActionsModel(Connection connection, int uid) {
		this.conn = connection;
		this.uid = uid;
		
		try {
    		PreparedStatement pstmt = conn.prepareStatement(GET_SQL);
    		pstmt.setInt(1, uid);
    		ResultSet actionsResultSet = pstmt.executeQuery();
    		while (actionsResultSet.next()) {
    			String serializedPhpAction = actionsResultSet.getString(1);
    			ASObject action = (ASObject)PhpDecoder.decode(serializedPhpAction);
    			actions.add(action);
    		}
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
	}
	
	public void destroy() {
		try {
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public ASObject[] getActions() {
		ArrayList<ASObject> allActions = new ArrayList<ASObject>();
		allActions.addAll(actions);
		allActions.addAll(addedActions);
		return allActions.toArray(new ASObject[0]);
    }

    public void addAction(ASObject action) {
    	addedActions.add(action);
    }

    public void save() {
    	try {
    		//"INSERT INTO farm_user_actions (row_user_action_id, income_action, vkontact_id, date) VALUES (NULL, ?, ?, ?)";
	    	PreparedStatement pstmt = conn.prepareStatement(ADD_SQL);
	    	
	    	for (ASObject act : addedActions) {    		
	    		pstmt.setString(1, PhpEncoder.serialize((ASObject)act));
	    		pstmt.setInt(2, uid);
	    		pstmt.setLong(3, System.currentTimeMillis()/1000);
	    		pstmt.addBatch();
	    	}
	    	pstmt.executeBatch();
	    	pstmt.close();
	    	
    	} catch (SQLException e) {
    		e.printStackTrace();
    	}
    }

    public void deleteActions(long beforeTimestamp) {
    	try {
	    	PreparedStatement pstmt = conn.prepareStatement(DELETE_SQL);
	    	pstmt.setInt(1, uid);
	    	pstmt.setLong(2, beforeTimestamp);
	    	pstmt.executeUpdate();
    	} catch (SQLException e) {
    		e.printStackTrace();
    	}
    }
}